<template>
  <div class="edit-page">
    <BaseButton @click="goBack">
        <ChevronsLeft class="icon-base" />
      </BaseButton>
    <h2 class="page-title">修改用户名</h2>
    <div class="form-group">
      <input type="text" placeholder="请输入新用户名" v-model="username" />
    </div>
    <button class="save-button"@click="updateUsername">保存修改</button>
  </div>
</template>



<script setup>
import { ref } from 'vue';
import BaseButton from '@/components/BaseButton.vue'
import { useRouter } from 'vue-router';
import basicDetailIcon from '@/assets/icons/basic-detail.svg';
import { ChevronsLeft } from 'lucide-vue-next'
import axios from 'axios'

const router = useRouter();
const username = ref('');
const icons = { basicDetail: basicDetailIcon };

const goBack = () => router.go(-1);

const updateUsername = async () => {
  if (!username.value.trim()) {
    alert('用户名不能为空');
    return;
  }

  const currentUser = JSON.parse(localStorage.getItem('user'));
  const userId = currentUser ? currentUser.uid : null;

  if (!userId) {
    alert('未找到当前用户，请重新登录');
    return;
  }

  try {
    const response = await axios.put('/api/auth/information/username', 
      {
        uid: userId,
        newName: username.value.trim()
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': localStorage.getItem('token')
        }
      }
    );

    if (response.data.code === 0) {
      // 更新本地存储的用户信息
      currentUser.uname = username.value.trim();
      localStorage.setItem('user', JSON.stringify(currentUser));

      alert('用户名修改成功');
      router.go(-1);
    } else {
      throw new Error(response.data.message || '修改失败');
    }
  } catch (error) {
    console.error('修改错误:', error);
    alert(error.response?.data?.message || error.message || '修改失败');
  }
};
</script>


<style scoped>
.edit-page {
  padding: var(--spacing-large);
  
}

.back-icon {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.icon-base {
  width: 24px;
  height: 24px;
  color: #1a1a1a;
}

.page-title {
  text-align: center;
  margin-top: 90px;
  font-size: var(--font-size-xlarge);
  color: #000;
}

input {
    width: 100%;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 14px;
    background-color: #fff;
    color: #333; /* 设置字体颜色 */
}

.save-button {
  width: 100%;
  padding: 15px;
  background-color: var(--primary-color);
  color: var(--text-light);
  border: none;
  border-radius: var(--border-radius-small);
  margin-top: 20px;
  cursor: pointer;
}
</style>
